
const MAX_LIMIT = 10
const db = wx.cloud.database()
const app = getApp()
Page({
  data: {
    swiperArr:[],
    playlist:[],
    newSong:[],
    artist:'',
    playingId: -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    this._getSwiper();
    this.ReadyLoadPlaylist();
    this.getNewSong();
  },
//获取新歌数据
getNewSong(){
  wx.cloud.callFunction({
    name:'music',
    data:{
      start: 0,
      count: MAX_LIMIT,
      $url:'getNewSongList'
    }
  }).then((res)=>{
   if(res){
     let data = res.result;
     for(let i = 0;i<data.length;i++){
       let artists = data[i].artists
       data[i].artists = this.formatArtist(artists)
      }
     this.setData({
       newSong:data
      })
      wx.setStorageSync('songlist', this.data.newSong)
      wx.hideLoading();
      wx.stopPullDownRefresh()
   }
  })
},

 async ReadyLoadPlaylist(){
  
    const playlist = await this.loadPlaylist(this.data.playlist.length,6);
    this.setData({
      playlist
    })
  },
 //加载歌单
  async loadPlaylist(start,count){
  let res =  await  wx.cloud.callFunction({
              name:'music',
              data:{
                start:start - 0,
                count:count -0,
                $url:'getPlaylist'
              }
            })
      
     return res.result.data
  },
  //格式化 artist 数据
  formatArtist(artists){
    for(let j = 0; j<artists.length;j++){
      var artStr='';
      artStr += artists[j].name+'/'
    }
     artStr =artStr.slice(0,artStr.length-1)
     return artStr
   },
   //前往歌单详情页面
   goMusicList(event){
    wx.navigateTo({
      url: `/pages/musiclist/musiclist?playlistId=${event.currentTarget.dataset.id}`,
    })
   },
   //选中歌曲高亮显示
  PlayingMusic(event){
    const ds =  event.currentTarget.dataset;
    let musicid =ds.musicid;
    this.setData({
      playingId:musicid,
    })
    wx.navigateTo({
      url: `/pages/player/player?musicId=${musicid}&flag=${ds.flag}&index=${ds.index}`,
    })

  },

  _getSwiper(){
    db.collection('swiper').get().then(res=>{
      this.setData({
        swiperArr:res.data
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getNewSong();
    // console.log(app.getMusicPlay())
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._getSwiper();
    this.getNewSong();
    this.loadPlaylist(0,6)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})